import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:xcite/core/utils/ali.dart';

import '../../core/models/spring_activity_model.dart';
import '../../core/providers/spring_activity_provider.dart';
import '../../core/providers/user_provider.dart';
import '../../core/utils/toast_helper.dart';
import '../../core/utils/popup_helper.dart';

class ActivityDetailScreen extends ConsumerStatefulWidget {
  final String activityId;

  const ActivityDetailScreen({super.key, required this.activityId});

  @override
  ConsumerState<ActivityDetailScreen> createState() =>
      _ActivityDetailScreenState();
}

class _ActivityDetailScreenState extends ConsumerState<ActivityDetailScreen> {
  SpringActivityEntity? activity;
  bool isLoading = false;

  @override
  void initState() {
    super.initState();
    _loadActivityData();
  }

  void _loadActivityData() {
    final activityNotifier = ref.read(springActivityProvider.notifier);
    activity = activityNotifier.getActivityById(widget.activityId);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (activity == null) {
      return Scaffold(
        body: Center(
          child: Text(
            'Activity not found',
          ).fontSize(16.sp).textColor(Colors.black),
        ),
      );
    }

    return Scaffold(
      body: Stack(
        children: [
          _buildBackgroundImage(),
          _buildTopNavigationBar(),
          _buildActivityTitleContainer(),
          _buildMainContentContainer(),
        ],
      ),
    );
  }

  Widget _buildBackgroundImage() {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: AspectRatio(
        aspectRatio: 414 / 409,
        child: Image.asset(
          'assets/resources/event.png',
          fit: BoxFit.cover,
          width: double.infinity,
          errorBuilder: (context, error, stackTrace) {
            return Container(
              color: const Color(0xFF2AB061),
              child:
                  Icon(Icons.event, size: 100.sp, color: Colors.white).center(),
            );
          },
        ),
      ),
    );
  }

  Widget _buildTopNavigationBar() {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: SafeArea(
        child: [
              Container(
                width: 30.w,
                height: 30.w,
                decoration: BoxDecoration(
                  color: Colors.black,
                  shape: BoxShape.circle,
                ),
                child:
                    Icon(
                      Icons.arrow_back_ios_new,
                    ).iconSize(20.sp).iconColor(Colors.white).center(),
              ).inkWell(onTap: () => GoRouter.of(context).pop()),
              Expanded(
                child: Text(
                  'Event Details',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 24.sp,
                    fontFamily: 'PoetsenOne',
                    fontWeight: FontWeight.w600,
                    color: Colors.black,
                  ),
                ),
              ),
              SizedBox(width: 40.w),
            ]
            .toRow(mainAxisAlignment: MainAxisAlignment.spaceBetween)
            .padding(horizontal: 16.w, vertical: 12.h),
      ),
    );
  }

  Widget _buildActivityTitleContainer() {
    final screenHeight = MediaQuery.of(context).size.height;
    final backgroundImageHeight = screenHeight * (409 / 844);

    return Positioned(
      left: 0.w,
      bottom: screenHeight - backgroundImageHeight + 20.h,
      child: Container(
        width: 348.w,
        height: 117.h,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/event_title.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: Text(activity!.title)
            .fontSize(22.sp)
            .fontFamily('PoetsenOne')
            .fontWeight(FontWeight.bold)
            .textColor(Colors.white)
            .padding(left: 10.w, top: 6.h)
            .alignment(Alignment.topLeft),
      ),
    );
  }

  Widget _buildMainContentContainer() {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: AspectRatio(
        aspectRatio: 414 / 597,
        child: Container(
          width: double.infinity,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/resources/event_main.png'),
              fit: BoxFit.fill,
            ),
          ),
          child: _buildContentColumn(),
        ),
      ),
    );
  }

  Widget _buildContentColumn() {
    return SingleChildScrollView(
      child: [
        SizedBox(height: 70.h),
        _buildDescriptionSection(),
        SizedBox(height: 12.h),
        _buildActivityInfoSection(),
        SizedBox(height: 40.h),
        _buildButtonSection(),
        SizedBox(height: 40.h),
      ].toColumn().padding(horizontal: 24.w),
    );
  }

  Widget _buildDescriptionSection() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/resources/activity_description.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: Text(
        activity!.description,
        style: TextStyle(fontSize: 14.sp, color: Colors.black87),
      ),
    );
  }

  Widget _buildActivityInfoSection() {
    return [
      Text(
        'Additional Information',
        style: TextStyle(
          fontSize: 24.sp,
          fontFamily: 'PoetsenOne',
          fontWeight: FontWeight.bold,
          color: Colors.white,
        ),
      ),
      SizedBox(height: 12.h),
      _buildInfoItem(AliIcons.iconTime, activity!.timeInfo),
      SizedBox(height: 8.h),
      _buildInfoItem(AliIcons.iconPeople, activity!.maxParticipants),
      SizedBox(height: 8.h),
      _buildInfoItem(AliIcons.iconLocalization, activity!.address),
      SizedBox(height: 8.h),
      _buildInfoItem(AliIcons.iconCar, activity!.travelMode),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
  }

  Widget _buildInfoItem(IconData icon, String value) {
    return [
      Icon(icon, size: 20.sp, color: Colors.white),
      SizedBox(width: 12.w),
      Expanded(
        child: Text(
          value,
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.white,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    ].toRow(crossAxisAlignment: CrossAxisAlignment.start);
  }

  Widget _buildButtonSection() {
    final currentUser = ref.watch(currentUserProvider);
    final isRegistered = ref.watch(
      isActivityRegisteredProvider({
        'userId': currentUser?.id ?? '',
        'activityId': activity!.activityId,
      }),
    );

    return [
      AspectRatio(
        aspectRatio: 374 / 56,
        child: Container(
          width: double.infinity,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(
                isRegistered
                    ? 'assets/resources/participate_button.png'
                    : 'assets/resources/participate_button.png',
              ),
              fit: BoxFit.fill,
            ),
          ),
        ).inkWell(onTap: _handleRegister),
      ),
      SizedBox(height: 16.h),
      AspectRatio(
        aspectRatio: 374 / 56,
        child: Container(
          width: double.infinity,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/resources/contact_button.png'),
              fit: BoxFit.fill,
            ),
          ),
        ).inkWell(onTap: _handleInquire),
      ),
    ].toColumn();
  }

  void _handleRegister() async {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) {
      PopupHelper.showLoginDialog(
        context,
        onLoginPressed: () {
          GoRouter.of(context).push('/login');
        },
        onCancelPressed: () {},
      );
      return;
    }

    ToastHelper.success('Sign up successful!', context: context);
  }

  void _handleInquire() {
    GoRouter.of(context).push('/activity-contact/${activity!.activityId}');
  }
}
